package org.meichao.utils;

import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.util.Date;

public class JWTUtils {

    private static Logger logger = LoggerFactory.getLogger(JWTUtils.class);

    //创建密钥
    private static final String SECRET_KEY = "boot.api.secret.key";

    //过期时间(1小时毫秒表示)
    private static final long TOKEN_EXPIRE_MILLIS = 1000 * 60 * 60;

    /**
     * 创建Json Web Token JWT
     * @param jsonObject
     * @return
     */
    public static String createJWT(JSONObject jsonObject){
        //指定签名算法
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long currentTimeMillis = System.currentTimeMillis();

        //生成密钥
        byte[] apiKeySecretByte = DatatypeConverter.parseBase64Binary(SECRET_KEY);
        SecretKeySpec secretKey = new SecretKeySpec(apiKeySecretByte,signatureAlgorithm.getJcaName());
        //生成token
        String token = Jwts.builder() //创建JWT对象
                //.setSubject("boot JWt") //设置主题
                //.setClaims(jsonObject) //默认下列设置的属性包含在Claims中
                .setId(jsonObject.toJSONString()) //设置自定义参数,如员工id等,以后可直接claims.getId()取
                .setIssuedAt(new Date(currentTimeMillis)) //设置签发时间
                .setExpiration(new Date(currentTimeMillis + TOKEN_EXPIRE_MILLIS)) //设置过期时间
                .signWith(signatureAlgorithm,secretKey) //设置安全密钥(生成签名的密钥和算法)
                .compact();//生成token(1.编码 Header 和 Payload 2.生成签名 3.拼接字符串)

        logger.info("生成token:{}",token);
        return token;
    }

    /**
     * 解析jwt
     * @param jwt
     * @return
     */
    public static Claims parseJWT(String jwt){
        Claims claims = Jwts.parser()
                .setSigningKey(DatatypeConverter.parseBase64Binary(SECRET_KEY))
                .parseClaimsJws(jwt).getBody();
        return claims;
    }


    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userKey", "1001");
        String token = createJWT(jsonObject);
        String userKey = JWTUtils.parseJWT(token).getId();
        logger.info("userKey:{}", userKey);
    }
}
